package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortEth;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.IElementPortEthService;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortEthSub;
import com.ruoyi.net.service.IElementPortEthSubService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-以太网子接口Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-以太网子接口")
@RestController
@RequestMapping("/element/port/eth/sub")
public class ElementPortEthSubController extends BaseController {
    @Autowired
    private IElementPortEthSubService elementPortEthSubService;

    @Autowired
    private IElementPortEthService elementPortEthService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-接口-以太网子接口列表
     */
    @ApiOperation(value = "读取网元-接口-以太网子接口列表", httpMethod = "GET")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortEthSub elementPortEthSub) {
        List<ElementPortEthSub> elementPortEthSubs = new ArrayList<>();
        if (StringUtils.isNotEmpty(elementPortEthSub.getPortEthId())) {
            ElementPortEth portEth = elementPortEthService.selectElementPortEthById(elementPortEthSub.getPortEthId());
            elementPortEthSub.setPortName(portEth.getPortName());
        }
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
        if (StringUtils.isNotEmpty(elementPortEthSub.getPortName())) {
            xml.append("        <name>").append(elementPortEthSub.getPortName()).append("</name>"); // 子主接口
        }
        xml.append("        <type>ETH-SUBIF</type>" + // 子主接口
//                        "        <enabled>enable</enabled>" + // 子主接口
                "      </interface>" +
                "    </interfaces>" +
                "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortEthSub.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortEthSub entity = new ElementPortEthSub();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setPortName(getXmlLabelValue(node, "name"));
                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
                    entity.setPortDesc(getXmlLabelValue(node, "description"));
//                    Node ethOption = getXmlLabelNode(node, "eth-option");
//                    entity.setMac(getXmlLabelValue(ethOption, "mac-address"));
//                    Node ethphyInterface = getXmlLabelNode(node, "ethphy-interface");
//                    entity.setTerminalSpeedType(getXmlLabelValue(ethphyInterface, "speed"));
//                    entity.setFiberOrCopper(getXmlLabelValue(ethphyInterface, "port-media-type"));
//                    entity.setWorkMode(getXmlLabelValue(ethphyInterface, "negotiation-enable"));
                    entity.setTerminalMode(getXmlLabelValue(node, "transport-layer"));
//                    entity.setMbps(getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    entity.setMaxFrameLen(getXmlLabelValue(ipNode, "ipv4-mtu"));
                    Node ipv4AddressListNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipv4AddressListNode != null) {
                        String ip = getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
                        entity.setIpForm(getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                    }
                    Node ifVlan = getXmlLabelNode(node, "if-vlan-cfg");
                    Node switchedNode = getXmlLabelNode(ifVlan, "vlan-sub-cfg");
                    entity.setVlanId(getXmlLabelValue(switchedNode, "svlan_min"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortEthSubs.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortEthSubs);
    }

    /**
     * 查询网元-接口-以太网子接口列表
     */
    @ApiOperation(value = "查询网元-接口-以太网子接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:sub:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortEthSub elementPortEthSub) {
        startPage();
        List<ElementPortEthSub> list = elementPortEthSubService.selectElementPortEthSubList(elementPortEthSub);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-以太网子接口列表
     */
    @ApiOperation(value = "导出网元-接口-以太网子接口列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:sub:export')")
    @Log(title = "网元-接口-以太网子接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortEthSub elementPortEthSub) {
        List<ElementPortEthSub> list = elementPortEthSubService.selectElementPortEthSubList(elementPortEthSub);
        ExcelUtil<ElementPortEthSub> util = new ExcelUtil<ElementPortEthSub>(ElementPortEthSub.class);
        util.exportExcel(response, list, "网元-接口-以太网子接口数据");
    }

    /**
     * 获取网元-接口-以太网子接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-以太网子接口详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:sub:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortEthSubService.selectElementPortEthSubById(id));
    }

    /**
     * 新增网元-接口-以太网子接口
     */
    @ApiOperation(value = "新增网元-接口-以太网子接口", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:sub:add')")
    @Log(title = "网元-接口-以太网子接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortEthSub elementPortEthSub) {
        return toAjax(elementPortEthSubService.insertElementPortEthSub(elementPortEthSub));
    }

    /**
     * 修改网元-接口-以太网子接口
     */
    @ApiOperation(value = "修改网元-接口-以太网子接口", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:sub:edit')")
    @Log(title = "网元-接口-以太网子接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortEthSub elementPortEthSub) {
        return toAjax(elementPortEthSubService.updateElementPortEthSub(elementPortEthSub));
    }

    /**
     * 删除网元-接口-以太网子接口
     */
    @ApiOperation(value = "删除网元-接口-以太网子接口", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:sub:remove')")
    @Log(title = "网元-接口-以太网子接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortEthSubService.deleteElementPortEthSubByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortEthSub entity = elementPortEthSubService.selectElementPortEthSubById(id);
        entity.setStatus("1");
        if (sendXml(entity)) {
            return toAjax(elementPortEthSubService.updateElementPortEthSub(entity));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortEthSub entity = elementPortEthSubService.selectElementPortEthSubById(id);
        entity.setStatus("0");
        if (sendXml(entity)) {
            return toAjax(elementPortEthSubService.updateElementPortEthSub(entity));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortEthSub entity) {
        boolean isSend = false;
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            ElementPortEth elementPortEth = elementPortEthService.selectElementPortEthById(entity.getPortEthId());
            // TODO: 2025/02/07 设备联调，已通过
            StringBuilder xml = new StringBuilder();
            if ("1".equals(entity.getStatus())) {
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"create\">" +
                        "        <name>" + elementPortEth.getPortName() + "." + entity.getSubPortName() + "</name>" +
                        "        <type>ETH-SUBIF</type>");
//                if (StringUtils.isNotEmpty(entity.getPortDesc())) {
//                    xml.append("        <description>" + entity.getPortDesc() + "</description>");
//                }
                xml.append("        <enabled>enable</enabled>" +
                        //2.11修改：比对验收项 2.11文档 无该节点，暂时先注释
//                        "        <eth-option xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-common\">" +
//                        "          <loop-block>disable</loop-block>" +
//                        "        </eth-option>" +
                        "        <transport-layer xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getTerminalMode() + "</transport-layer>");

                xml.append("        <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                        "          <ipv4-mtu>" + (StringUtils.isEmpty(entity.getMaxFrameLen()) ? 1500 : entity.getMaxFrameLen()) + "</ipv4-mtu>"); //取值46-9600
                //2.11修改：比对验收项 2.11文档 无该节点，暂时先注释
               /* if (StringUtils.isNotEmpty(entity.getIp()) && StringUtils.isNotEmpty(entity.getMask())) {
                    xml.append("           <ipv4-address-list>" +
                            "               <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                            "               <secondry-use>mast</secondry-use>" + // entity.getIpForm()
                            "           </ipv4-address-list>");
                }*/
                xml.append("        </ip>");
                if (StringUtils.isNotEmpty(entity.getVlanId())) {
                    xml.append("        <if-vlan-cfg xmlns=\"http://fiberhome.com/fhnw/yang/ethernetservice/fos-vlan\">" +
                            "          <termination_type>dot1q</termination_type>" +
                            "          <vlan-sub-cfg>" +
                            "            <svlan_min>" + entity.getVlanId() + "</svlan_min>" +//取值范围 2-4092
                            "          </vlan-sub-cfg>" +
                            "        </if-vlan-cfg>");
                }
                xml.append("        <qos-policy-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\"/>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
            } else {
                // 去激活
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">" +
                        "        <name>" + elementPortEth.getPortName() + "." + entity.getSubPortName() + "</name>" +
                        "        <type>ETH-SUBIF</type>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
            }
            logger.info("以太主接口-子接口激活xml:" + xml);
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}